{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# **PDF RAG**\n",
        "\n",
        "Authored by [Kalyan KS](https://www.linkedin.com/in/kalyanksnlp/). To stay updated with LLM, RAG and Agent updates, you can follow me on [Twitter](https://x.com/kalyan_kpl).\n",
        "\n",
        "- Step-1 : Extract the PDF text\n",
        "- Step-2 : Chunk the extracted PDF text\n",
        "- Step-3 : Create a vector store with the PDF chunks\n",
        "- Step-4 : Create a retriever which returns the relevant chunks\n",
        "- Step-5 : Build context from the relevant chunk texts\n",
        "- Step-6 : Build the RAG chain using rag prompt, LLM and string output parser.\n",
        "- Step-7 : Run the RAG chain to get the answer."
      ],
      "metadata": {
        "id": "bkvZp-8oJxfb"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Install and import libraries**\n",
        "\n",
        "- PyPDFLoader uses `pypdf` python library to extract text from PDF document."
      ],
      "metadata": {
        "id": "WX1Zty3aK8dF"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install -qU langchain langchain-community langchain-text-splitters\n",
        "!pip install -qU langchain-openai langchain-chroma pypdf"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ieCqdSLiK-3V",
        "outputId": "add5789d-6aef-40ae-f2f6-a266926a4697"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/2.5 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[91m━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.5/2.5 MB\u001b[0m \u001b[31m15.5 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K   \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m2.5/2.5 MB\u001b[0m \u001b[31m40.3 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.5/2.5 MB\u001b[0m \u001b[31m25.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m50.9/50.9 kB\u001b[0m \u001b[31m3.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m67.3/67.3 kB\u001b[0m \u001b[31m3.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
            "  Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
            "  Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m55.0/55.0 kB\u001b[0m \u001b[31m3.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m300.7/300.7 kB\u001b[0m \u001b[31m10.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m611.1/611.1 kB\u001b[0m \u001b[31m21.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.4/2.4 MB\u001b[0m \u001b[31m50.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.2/1.2 MB\u001b[0m \u001b[31m46.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m278.6/278.6 kB\u001b[0m \u001b[31m15.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m94.8/94.8 kB\u001b[0m \u001b[31m5.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.0/2.0 MB\u001b[0m \u001b[31m59.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m101.6/101.6 kB\u001b[0m \u001b[31m6.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m13.3/13.3 MB\u001b[0m \u001b[31m68.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m55.9/55.9 kB\u001b[0m \u001b[31m3.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m177.4/177.4 kB\u001b[0m \u001b[31m12.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m65.0/65.0 kB\u001b[0m \u001b[31m3.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m118.7/118.7 kB\u001b[0m \u001b[31m7.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m73.0/73.0 kB\u001b[0m \u001b[31m3.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m62.3/62.3 kB\u001b[0m \u001b[31m3.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m459.8/459.8 kB\u001b[0m \u001b[31m25.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m319.7/319.7 kB\u001b[0m \u001b[31m17.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m71.5/71.5 kB\u001b[0m \u001b[31m5.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.0/4.0 MB\u001b[0m \u001b[31m76.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m452.6/452.6 kB\u001b[0m \u001b[31m27.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m46.0/46.0 kB\u001b[0m \u001b[31m2.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m86.8/86.8 kB\u001b[0m \u001b[31m4.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Building wheel for pypika (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain_community.document_loaders import PyPDFLoader\n",
        "from langchain_text_splitters  import RecursiveCharacterTextSplitter\n",
        "from langchain_chroma import Chroma\n",
        "from langchain_openai import OpenAIEmbeddings, ChatOpenAI\n",
        "from langchain_core.prompts import ChatPromptTemplate\n",
        "from langchain_core.output_parsers import StrOutputParser\n",
        "from langchain_core.runnables import RunnableLambda"
      ],
      "metadata": {
        "id": "TXetwTFYLA8X"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Set up LLM API Key**\n",
        "\n",
        "- Save the `OPENAI_API_KEY` in Google Colab Secrets"
      ],
      "metadata": {
        "id": "bg-Xr6WgLBVj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import userdata\n",
        "import os\n",
        "os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY')"
      ],
      "metadata": {
        "id": "pnsVEcU1LFwZ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Extract PDF text**"
      ],
      "metadata": {
        "id": "0MwnhbIrLIHf"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Download the PDF file\n",
        "import requests\n",
        "\n",
        "pdf_url = 'https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf'\n",
        "response = requests.get(pdf_url)\n",
        "\n",
        "pdf_path = 'attention_is_all_you_need.pdf'\n",
        "with open(pdf_path, 'wb') as file:\n",
        "    file.write(response.content)"
      ],
      "metadata": {
        "id": "zm28zN5yQZUI"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from typing import List\n",
        "from langchain.schema import Document\n",
        "\n",
        "def pdf_extract(pdf_path: str) -> List[Document]:\n",
        "    \"\"\"\n",
        "    Extracts text from a PDF file using PyPDFLoader.\n",
        "\n",
        "    Parameters:\n",
        "    pdf_path (str): The file path of the PDF to be extracted.\n",
        "\n",
        "    Returns:\n",
        "    List[Document]: A list of Document objects containing the extracted text from the PDF.\n",
        "    \"\"\"\n",
        "\n",
        "    print(\"PDF file text is extracted...\")\n",
        "    loader = PyPDFLoader(pdf_path)\n",
        "    pdf_text = loader.load()\n",
        "\n",
        "    return pdf_text"
      ],
      "metadata": {
        "id": "HBpkh5fALREj"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "pdf_text = pdf_extract(pdf_path)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "vnHyVr2HQeJa",
        "outputId": "86afd533-1f6d-4629-bb5b-2ba89e48abf9"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "PDF file text is extracted...\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(pdf_text)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Y_fb-lCUap4X",
        "outputId": "2351739a-51e8-4368-e2e0-65193c3f3e52"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 0, 'page_label': '1'}, page_content='Attention Is All You Need\\nAshish Vaswani∗\\nGoogle Brain\\navaswani@google.com\\nNoam Shazeer∗\\nGoogle Brain\\nnoam@google.com\\nNiki Parmar∗\\nGoogle Research\\nnikip@google.com\\nJakob Uszkoreit∗\\nGoogle Research\\nusz@google.com\\nLlion Jones∗\\nGoogle Research\\nllion@google.com\\nAidan N. Gomez∗†\\nUniversity of Toronto\\naidan@cs.toronto.edu\\nŁukasz Kaiser ∗\\nGoogle Brain\\nlukaszkaiser@google.com\\nIllia Polosukhin∗‡\\nillia.polosukhin@gmail.com\\nAbstract\\nThe dominant sequence transduction models are based on complex recurrent or\\nconvolutional neural networks that include an encoder and a decoder. The best\\nperforming models also connect the encoder and decoder through an attention\\nmechanism. We propose a new simple network architecture, the Transformer,\\nbased solely on attention mechanisms, dispensing with recurrence and convolutions\\nentirely. Experiments on two machine translation tasks show these models to\\nbe superior in quality while being more parallelizable and requiring signiﬁcantly\\nless time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-\\nto-German translation task, improving over the existing best results, including\\nensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task,\\nour model establishes a new single-model state-of-the-art BLEU score of 41.0 after\\ntraining for 3.5 days on eight GPUs, a small fraction of the training costs of the\\nbest models from the literature.\\n1 Introduction\\nRecurrent neural networks, long short-term memory [12] and gated recurrent [7] neural networks\\nin particular, have been ﬁrmly established as state of the art approaches in sequence modeling and\\ntransduction problems such as language modeling and machine translation [ 29, 2, 5]. Numerous\\nefforts have since continued to push the boundaries of recurrent language models and encoder-decoder\\narchitectures [31, 21, 13].\\n∗Equal contribution. Listing order is random. Jakob proposed replacing RNNs with self-attention and started\\nthe effort to evaluate this idea. Ashish, with Illia, designed and implemented the ﬁrst Transformer models and\\nhas been crucially involved in every aspect of this work. Noam proposed scaled dot-product attention, multi-head\\nattention and the parameter-free position representation and became the other person involved in nearly every\\ndetail. Niki designed, implemented, tuned and evaluated countless model variants in our original codebase and\\ntensor2tensor. Llion also experimented with novel model variants, was responsible for our initial codebase, and\\nefﬁcient inference and visualizations. Lukasz and Aidan spent countless long days designing various parts of and\\nimplementing tensor2tensor, replacing our earlier codebase, greatly improving results and massively accelerating\\nour research.\\n†Work performed while at Google Brain.\\n‡Work performed while at Google Research.\\n31st Conference on Neural Information Processing Systems (NIPS 2017), Long Beach, CA, USA.'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 1, 'page_label': '2'}, page_content='Recurrent models typically factor computation along the symbol positions of the input and output\\nsequences. Aligning the positions to steps in computation time, they generate a sequence of hidden\\nstates ht, as a function of the previous hidden state ht−1 and the input for position t. This inherently\\nsequential nature precludes parallelization within training examples, which becomes critical at longer\\nsequence lengths, as memory constraints limit batching across examples. Recent work has achieved\\nsigniﬁcant improvements in computational efﬁciency through factorization tricks [18] and conditional\\ncomputation [26], while also improving model performance in case of the latter. The fundamental\\nconstraint of sequential computation, however, remains.\\nAttention mechanisms have become an integral part of compelling sequence modeling and transduc-\\ntion models in various tasks, allowing modeling of dependencies without regard to their distance in\\nthe input or output sequences [2, 16]. In all but a few cases [22], however, such attention mechanisms\\nare used in conjunction with a recurrent network.\\nIn this work we propose the Transformer, a model architecture eschewing recurrence and instead\\nrelying entirely on an attention mechanism to draw global dependencies between input and output.\\nThe Transformer allows for signiﬁcantly more parallelization and can reach a new state of the art in\\ntranslation quality after being trained for as little as twelve hours on eight P100 GPUs.\\n2 Background\\nThe goal of reducing sequential computation also forms the foundation of the Extended Neural GPU\\n[20], ByteNet [15] and ConvS2S [8], all of which use convolutional neural networks as basic building\\nblock, computing hidden representations in parallel for all input and output positions. In these models,\\nthe number of operations required to relate signals from two arbitrary input or output positions grows\\nin the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes\\nit more difﬁcult to learn dependencies between distant positions [ 11]. In the Transformer this is\\nreduced to a constant number of operations, albeit at the cost of reduced effective resolution due\\nto averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as\\ndescribed in section 3.2.\\nSelf-attention, sometimes called intra-attention is an attention mechanism relating different positions\\nof a single sequence in order to compute a representation of the sequence. Self-attention has been\\nused successfully in a variety of tasks including reading comprehension, abstractive summarization,\\ntextual entailment and learning task-independent sentence representations [4, 22, 23, 19].\\nEnd-to-end memory networks are based on a recurrent attention mechanism instead of sequence-\\naligned recurrence and have been shown to perform well on simple-language question answering and\\nlanguage modeling tasks [28].\\nTo the best of our knowledge, however, the Transformer is the ﬁrst transduction model relying\\nentirely on self-attention to compute representations of its input and output without using sequence-\\naligned RNNs or convolution. In the following sections, we will describe the Transformer, motivate\\nself-attention and discuss its advantages over models such as [14, 15] and [8].\\n3 Model Architecture\\nMost competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 29].\\nHere, the encoder maps an input sequence of symbol representations (x1,...,x n) to a sequence\\nof continuous representations z = (z1,...,z n). Given z, the decoder then generates an output\\nsequence (y1,...,y m) of symbols one element at a time. At each step the model is auto-regressive\\n[9], consuming the previously generated symbols as additional input when generating the next.\\nThe Transformer follows this overall architecture using stacked self-attention and point-wise, fully\\nconnected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\\nrespectively.\\n3.1 Encoder and Decoder Stacks\\nEncoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two\\nsub-layers. The ﬁrst is a multi-head self-attention mechanism, and the second is a simple, position-\\n2'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 2, 'page_label': '3'}, page_content='Figure 1: The Transformer - model architecture.\\nwise fully connected feed-forward network. We employ a residual connection [10] around each of\\nthe two sub-layers, followed by layer normalization [ 1]. That is, the output of each sub-layer is\\nLayerNorm(x+ Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer\\nitself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding\\nlayers, produce outputs of dimension dmodel = 512.\\nDecoder: The decoder is also composed of a stack of N = 6identical layers. In addition to the two\\nsub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head\\nattention over the output of the encoder stack. Similar to the encoder, we employ residual connections\\naround each of the sub-layers, followed by layer normalization. We also modify the self-attention\\nsub-layer in the decoder stack to prevent positions from attending to subsequent positions. This\\nmasking, combined with fact that the output embeddings are offset by one position, ensures that the\\npredictions for position ican depend only on the known outputs at positions less than i.\\n3.2 Attention\\nAn attention function can be described as mapping a query and a set of key-value pairs to an output,\\nwhere the query, keys, values, and output are all vectors. The output is computed as a weighted sum\\nof the values, where the weight assigned to each value is computed by a compatibility function of the\\nquery with the corresponding key.\\n3.2.1 Scaled Dot-Product Attention\\nWe call our particular attention \"Scaled Dot-Product Attention\" (Figure 2). The input consists of\\nqueries and keys of dimension dk, and values of dimension dv. We compute the dot products of the\\n3'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 3, 'page_label': '4'}, page_content='Scaled Dot-Product Attention\\n Multi-Head Attention\\nFigure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several\\nattention layers running in parallel.\\nquery with all keys, divide each by √dk, and apply a softmax function to obtain the weights on the\\nvalues.\\nIn practice, we compute the attention function on a set of queries simultaneously, packed together\\ninto a matrix Q. The keys and values are also packed together into matrices Kand V. We compute\\nthe matrix of outputs as:\\nAttention(Q,K,V ) = softmax(QKT\\n√dk\\n)V (1)\\nThe two most commonly used attention functions are additive attention [2], and dot-product (multi-\\nplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor\\nof 1√dk\\n. Additive attention computes the compatibility function using a feed-forward network with\\na single hidden layer. While the two are similar in theoretical complexity, dot-product attention is\\nmuch faster and more space-efﬁcient in practice, since it can be implemented using highly optimized\\nmatrix multiplication code.\\nWhile for small values of dk the two mechanisms perform similarly, additive attention outperforms\\ndot product attention without scaling for larger values of dk [3]. We suspect that for large values of\\ndk, the dot products grow large in magnitude, pushing the softmax function into regions where it has\\nextremely small gradients 4. To counteract this effect, we scale the dot products by 1√dk\\n.\\n3.2.2 Multi-Head Attention\\nInstead of performing a single attention function with dmodel-dimensional keys, values and queries,\\nwe found it beneﬁcial to linearly project the queries, keys and values htimes with different, learned\\nlinear projections to dk, dk and dv dimensions, respectively. On each of these projected versions of\\nqueries, keys and values we then perform the attention function in parallel, yielding dv-dimensional\\noutput values. These are concatenated and once again projected, resulting in the ﬁnal values, as\\ndepicted in Figure 2.\\nMulti-head attention allows the model to jointly attend to information from different representation\\nsubspaces at different positions. With a single attention head, averaging inhibits this.\\n4To illustrate why the dot products get large, assume that the components of q and k are independent random\\nvariables with mean 0 and variance 1. Then their dot product, q · k = ∑dk\\ni=1 qiki, has mean 0 and variance dk.\\n4'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 4, 'page_label': '5'}, page_content='MultiHead(Q,K,V ) = Concat(head1,..., headh)WO\\nwhere headi = Attention(QWQ\\ni ,KW K\\ni ,VW V\\ni )\\nWhere the projections are parameter matricesWQ\\ni ∈Rdmodel×dk , WK\\ni ∈Rdmodel×dk , WV\\ni ∈Rdmodel×dv\\nand WO ∈Rhdv×dmodel .\\nIn this work we employ h = 8 parallel attention layers, or heads. For each of these we use\\ndk = dv = dmodel/h= 64. Due to the reduced dimension of each head, the total computational cost\\nis similar to that of single-head attention with full dimensionality.\\n3.2.3 Applications of Attention in our Model\\nThe Transformer uses multi-head attention in three different ways:\\n• In \"encoder-decoder attention\" layers, the queries come from the previous decoder layer,\\nand the memory keys and values come from the output of the encoder. This allows every\\nposition in the decoder to attend over all positions in the input sequence. This mimics the\\ntypical encoder-decoder attention mechanisms in sequence-to-sequence models such as\\n[31, 2, 8].\\n• The encoder contains self-attention layers. In a self-attention layer all of the keys, values\\nand queries come from the same place, in this case, the output of the previous layer in the\\nencoder. Each position in the encoder can attend to all positions in the previous layer of the\\nencoder.\\n• Similarly, self-attention layers in the decoder allow each position in the decoder to attend to\\nall positions in the decoder up to and including that position. We need to prevent leftward\\ninformation ﬂow in the decoder to preserve the auto-regressive property. We implement this\\ninside of scaled dot-product attention by masking out (setting to −∞) all values in the input\\nof the softmax which correspond to illegal connections. See Figure 2.\\n3.3 Position-wise Feed-Forward Networks\\nIn addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully\\nconnected feed-forward network, which is applied to each position separately and identically. This\\nconsists of two linear transformations with a ReLU activation in between.\\nFFN(x) = max(0,xW1 + b1)W2 + b2 (2)\\nWhile the linear transformations are the same across different positions, they use different parameters\\nfrom layer to layer. Another way of describing this is as two convolutions with kernel size 1.\\nThe dimensionality of input and output is dmodel = 512, and the inner-layer has dimensionality\\ndff = 2048.\\n3.4 Embeddings and Softmax\\nSimilarly to other sequence transduction models, we use learned embeddings to convert the input\\ntokens and output tokens to vectors of dimension dmodel. We also use the usual learned linear transfor-\\nmation and softmax function to convert the decoder output to predicted next-token probabilities. In\\nour model, we share the same weight matrix between the two embedding layers and the pre-softmax\\nlinear transformation, similar to [24]. In the embedding layers, we multiply those weights by √dmodel.\\n3.5 Positional Encoding\\nSince our model contains no recurrence and no convolution, in order for the model to make use of the\\norder of the sequence, we must inject some information about the relative or absolute position of the\\ntokens in the sequence. To this end, we add \"positional encodings\" to the input embeddings at the\\n5'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 5, 'page_label': '6'}, page_content='Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations\\nfor different layer types. nis the sequence length, dis the representation dimension, kis the kernel\\nsize of convolutions and rthe size of the neighborhood in restricted self-attention.\\nLayer Type Complexity per Layer Sequential Maximum Path Length\\nOperations\\nSelf-Attention O(n2 ·d) O(1) O(1)\\nRecurrent O(n·d2) O(n) O(n)\\nConvolutional O(k·n·d2) O(1) O(logk(n))\\nSelf-Attention (restricted) O(r·n·d) O(1) O(n/r)\\nbottoms of the encoder and decoder stacks. The positional encodings have the same dimension dmodel\\nas the embeddings, so that the two can be summed. There are many choices of positional encodings,\\nlearned and ﬁxed [8].\\nIn this work, we use sine and cosine functions of different frequencies:\\nPE(pos,2i) = sin(pos/100002i/dmodel )\\nPE(pos,2i+1) = cos(pos/100002i/dmodel )\\nwhere posis the position and iis the dimension. That is, each dimension of the positional encoding\\ncorresponds to a sinusoid. The wavelengths form a geometric progression from 2πto 10000 ·2π. We\\nchose this function because we hypothesized it would allow the model to easily learn to attend by\\nrelative positions, since for any ﬁxed offset k, PEpos+k can be represented as a linear function of\\nPEpos.\\nWe also experimented with using learned positional embeddings [8] instead, and found that the two\\nversions produced nearly identical results (see Table 3 row (E)). We chose the sinusoidal version\\nbecause it may allow the model to extrapolate to sequence lengths longer than the ones encountered\\nduring training.\\n4 Why Self-Attention\\nIn this section we compare various aspects of self-attention layers to the recurrent and convolu-\\ntional layers commonly used for mapping one variable-length sequence of symbol representations\\n(x1,...,x n) to another sequence of equal length (z1,...,z n), with xi,zi ∈Rd, such as a hidden\\nlayer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we\\nconsider three desiderata.\\nOne is the total computational complexity per layer. Another is the amount of computation that can\\nbe parallelized, as measured by the minimum number of sequential operations required.\\nThe third is the path length between long-range dependencies in the network. Learning long-range\\ndependencies is a key challenge in many sequence transduction tasks. One key factor affecting the\\nability to learn such dependencies is the length of the paths forward and backward signals have to\\ntraverse in the network. The shorter these paths between any combination of positions in the input\\nand output sequences, the easier it is to learn long-range dependencies [11]. Hence we also compare\\nthe maximum path length between any two input and output positions in networks composed of the\\ndifferent layer types.\\nAs noted in Table 1, a self-attention layer connects all positions with a constant number of sequentially\\nexecuted operations, whereas a recurrent layer requires O(n) sequential operations. In terms of\\ncomputational complexity, self-attention layers are faster than recurrent layers when the sequence\\nlength n is smaller than the representation dimensionality d, which is most often the case with\\nsentence representations used by state-of-the-art models in machine translations, such as word-piece\\n[31] and byte-pair [25] representations. To improve computational performance for tasks involving\\nvery long sequences, self-attention could be restricted to considering only a neighborhood of size rin\\n6'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 6, 'page_label': '7'}, page_content='the input sequence centered around the respective output position. This would increase the maximum\\npath length to O(n/r). We plan to investigate this approach further in future work.\\nA single convolutional layer with kernel width k<n does not connect all pairs of input and output\\npositions. Doing so requires a stack of O(n/k) convolutional layers in the case of contiguous kernels,\\nor O(logk(n)) in the case of dilated convolutions [ 15], increasing the length of the longest paths\\nbetween any two positions in the network. Convolutional layers are generally more expensive than\\nrecurrent layers, by a factor of k. Separable convolutions [ 6], however, decrease the complexity\\nconsiderably, to O(k·n·d+ n·d2). Even with k = n, however, the complexity of a separable\\nconvolution is equal to the combination of a self-attention layer and a point-wise feed-forward layer,\\nthe approach we take in our model.\\nAs side beneﬁt, self-attention could yield more interpretable models. We inspect attention distributions\\nfrom our models and present and discuss examples in the appendix. Not only do individual attention\\nheads clearly learn to perform different tasks, many appear to exhibit behavior related to the syntactic\\nand semantic structure of the sentences.\\n5 Training\\nThis section describes the training regime for our models.\\n5.1 Training Data and Batching\\nWe trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million\\nsentence pairs. Sentences were encoded using byte-pair encoding [ 3], which has a shared source-\\ntarget vocabulary of about 37000 tokens. For English-French, we used the signiﬁcantly larger WMT\\n2014 English-French dataset consisting of 36M sentences and split tokens into a 32000 word-piece\\nvocabulary [31]. Sentence pairs were batched together by approximate sequence length. Each training\\nbatch contained a set of sentence pairs containing approximately 25000 source tokens and 25000\\ntarget tokens.\\n5.2 Hardware and Schedule\\nWe trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using\\nthe hyperparameters described throughout the paper, each training step took about 0.4 seconds. We\\ntrained the base models for a total of 100,000 steps or 12 hours. For our big models,(described on the\\nbottom line of table 3), step time was 1.0 seconds. The big models were trained for 300,000 steps\\n(3.5 days).\\n5.3 Optimizer\\nWe used the Adam optimizer [17] with β1 = 0.9, β2 = 0.98 and ϵ= 10−9. We varied the learning\\nrate over the course of training, according to the formula:\\nlrate= d−0.5\\nmodel ·min(step_num−0.5,step_num·warmup_steps−1.5) (3)\\nThis corresponds to increasing the learning rate linearly for the ﬁrst warmup_stepstraining steps,\\nand decreasing it thereafter proportionally to the inverse square root of the step number. We used\\nwarmup_steps= 4000.\\n5.4 Regularization\\nWe employ three types of regularization during training:\\nResidual Dropout We apply dropout [27] to the output of each sub-layer, before it is added to the\\nsub-layer input and normalized. In addition, we apply dropout to the sums of the embeddings and the\\npositional encodings in both the encoder and decoder stacks. For the base model, we use a rate of\\nPdrop = 0.1.\\n7'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 7, 'page_label': '8'}, page_content='Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the\\nEnglish-to-German and English-to-French newstest2014 tests at a fraction of the training cost.\\nModel\\nBLEU Training Cost (FLOPs)\\nEN-DE EN-FR EN-DE EN-FR\\nByteNet [15] 23.75\\nDeep-Att + PosUnk [32] 39.2 1.0 ·1020\\nGNMT + RL [31] 24.6 39.92 2.3 ·1019 1.4 ·1020\\nConvS2S [8] 25.16 40.46 9.6 ·1018 1.5 ·1020\\nMoE [26] 26.03 40.56 2.0 ·1019 1.2 ·1020\\nDeep-Att + PosUnk Ensemble [32] 40.4 8.0 ·1020\\nGNMT + RL Ensemble [31] 26.30 41.16 1.8 ·1020 1.1 ·1021\\nConvS2S Ensemble [8] 26.36 41.29 7.7 ·1019 1.2 ·1021\\nTransformer (base model) 27.3 38.1 3.3 · 1018\\nTransformer (big) 28.4 41.0 2.3 ·1019\\nLabel Smoothing During training, we employed label smoothing of value ϵls = 0.1 [30]. This\\nhurts perplexity, as the model learns to be more unsure, but improves accuracy and BLEU score.\\n6 Results\\n6.1 Machine Translation\\nOn the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big)\\nin Table 2) outperforms the best previously reported models (including ensembles) by more than 2.0\\nBLEU, establishing a new state-of-the-art BLEU score of 28.4. The conﬁguration of this model is\\nlisted in the bottom line of Table 3. Training took 3.5 days on 8 P100 GPUs. Even our base model\\nsurpasses all previously published models and ensembles, at a fraction of the training cost of any of\\nthe competitive models.\\nOn the WMT 2014 English-to-French translation task, our big model achieves a BLEU score of 41.0,\\noutperforming all of the previously published single models, at less than 1/4 the training cost of the\\nprevious state-of-the-art model. The Transformer (big) model trained for English-to-French used\\ndropout rate Pdrop = 0.1, instead of 0.3.\\nFor the base models, we used a single model obtained by averaging the last 5 checkpoints, which\\nwere written at 10-minute intervals. For the big models, we averaged the last 20 checkpoints. We\\nused beam search with a beam size of 4 and length penalty α= 0.6 [31]. These hyperparameters\\nwere chosen after experimentation on the development set. We set the maximum output length during\\ninference to input length + 50, but terminate early when possible [31].\\nTable 2 summarizes our results and compares our translation quality and training costs to other model\\narchitectures from the literature. We estimate the number of ﬂoating point operations used to train a\\nmodel by multiplying the training time, the number of GPUs used, and an estimate of the sustained\\nsingle-precision ﬂoating-point capacity of each GPU 5.\\n6.2 Model Variations\\nTo evaluate the importance of different components of the Transformer, we varied our base model\\nin different ways, measuring the change in performance on English-to-German translation on the\\ndevelopment set, newstest2013. We used beam search as described in the previous section, but no\\ncheckpoint averaging. We present these results in Table 3.\\nIn Table 3 rows (A), we vary the number of attention heads and the attention key and value dimensions,\\nkeeping the amount of computation constant, as described in Section 3.2.2. While single-head\\nattention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads.\\n5We used values of 2.8, 3.7, 6.0 and 9.5 TFLOPS for K80, K40, M40 and P100, respectively.\\n8'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 8, 'page_label': '9'}, page_content='Table 3: Variations on the Transformer architecture. Unlisted values are identical to those of the base\\nmodel. All metrics are on the English-to-German translation development set, newstest2013. Listed\\nperplexities are per-wordpiece, according to our byte-pair encoding, and should not be compared to\\nper-word perplexities.\\nN d model dff h d k dv Pdrop ϵls\\ntrain PPL BLEU params\\nsteps (dev) (dev) ×106\\nbase 6 512 2048 8 64 64 0.1 0.1 100K 4.92 25.8 65\\n(A)\\n1 512 512 5.29 24.9\\n4 128 128 5.00 25.5\\n16 32 32 4.91 25.8\\n32 16 16 5.01 25.4\\n(B) 16 5.16 25.1 58\\n32 5.01 25.4 60\\n(C)\\n2 6.11 23.7 36\\n4 5.19 25.3 50\\n8 4.88 25.5 80\\n256 32 32 5.75 24.5 28\\n1024 128 128 4.66 26.0 168\\n1024 5.12 25.4 53\\n4096 4.75 26.2 90\\n(D)\\n0.0 5.77 24.6\\n0.2 4.95 25.5\\n0.0 4.67 25.3\\n0.2 5.47 25.7\\n(E) positional embedding instead of sinusoids 4.92 25.7\\nbig 6 1024 4096 16 0.3 300K 4.33 26.4 213\\nIn Table 3 rows (B), we observe that reducing the attention key size dk hurts model quality. This\\nsuggests that determining compatibility is not easy and that a more sophisticated compatibility\\nfunction than dot product may be beneﬁcial. We further observe in rows (C) and (D) that, as expected,\\nbigger models are better, and dropout is very helpful in avoiding over-ﬁtting. In row (E) we replace our\\nsinusoidal positional encoding with learned positional embeddings [8], and observe nearly identical\\nresults to the base model.\\n7 Conclusion\\nIn this work, we presented the Transformer, the ﬁrst sequence transduction model based entirely on\\nattention, replacing the recurrent layers most commonly used in encoder-decoder architectures with\\nmulti-headed self-attention.\\nFor translation tasks, the Transformer can be trained signiﬁcantly faster than architectures based\\non recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014\\nEnglish-to-French translation tasks, we achieve a new state of the art. In the former task our best\\nmodel outperforms even all previously reported ensembles.\\nWe are excited about the future of attention-based models and plan to apply them to other tasks. We\\nplan to extend the Transformer to problems involving input and output modalities other than text and\\nto investigate local, restricted attention mechanisms to efﬁciently handle large inputs and outputs\\nsuch as images, audio and video. Making generation less sequential is another research goals of ours.\\nThe code we used to train and evaluate our models is available at https://github.com/\\ntensorflow/tensor2tensor.\\nAcknowledgements We are grateful to Nal Kalchbrenner and Stephan Gouws for their fruitful\\ncomments, corrections and inspiration.\\n9'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 9, 'page_label': '10'}, page_content='References\\n[1] Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint\\narXiv:1607.06450, 2016.\\n[2] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly\\nlearning to align and translate. CoRR, abs/1409.0473, 2014.\\n[3] Denny Britz, Anna Goldie, Minh-Thang Luong, and Quoc V . Le. Massive exploration of neural\\nmachine translation architectures. CoRR, abs/1703.03906, 2017.\\n[4] Jianpeng Cheng, Li Dong, and Mirella Lapata. Long short-term memory-networks for machine\\nreading. arXiv preprint arXiv:1601.06733, 2016.\\n[5] Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Fethi Bougares, Holger Schwenk,\\nand Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical\\nmachine translation. CoRR, abs/1406.1078, 2014.\\n[6] Francois Chollet. Xception: Deep learning with depthwise separable convolutions. arXiv\\npreprint arXiv:1610.02357, 2016.\\n[7] Junyoung Chung, Çaglar Gülçehre, Kyunghyun Cho, and Yoshua Bengio. Empirical evaluation\\nof gated recurrent neural networks on sequence modeling. CoRR, abs/1412.3555, 2014.\\n[8] Jonas Gehring, Michael Auli, David Grangier, Denis Yarats, and Yann N. Dauphin. Convolu-\\ntional sequence to sequence learning. arXiv preprint arXiv:1705.03122v2, 2017.\\n[9] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint\\narXiv:1308.0850, 2013.\\n[10] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for im-\\nage recognition. In Proceedings of the IEEE Conference on Computer Vision and Pattern\\nRecognition, pages 770–778, 2016.\\n[11] Sepp Hochreiter, Yoshua Bengio, Paolo Frasconi, and Jürgen Schmidhuber. Gradient ﬂow in\\nrecurrent nets: the difﬁculty of learning long-term dependencies, 2001.\\n[12] Sepp Hochreiter and Jürgen Schmidhuber. Long short-term memory. Neural computation,\\n9(8):1735–1780, 1997.\\n[13] Rafal Jozefowicz, Oriol Vinyals, Mike Schuster, Noam Shazeer, and Yonghui Wu. Exploring\\nthe limits of language modeling. arXiv preprint arXiv:1602.02410, 2016.\\n[14] Łukasz Kaiser and Ilya Sutskever. Neural GPUs learn algorithms. In International Conference\\non Learning Representations (ICLR), 2016.\\n[15] Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Ko-\\nray Kavukcuoglu. Neural machine translation in linear time.arXiv preprint arXiv:1610.10099v2,\\n2017.\\n[16] Yoon Kim, Carl Denton, Luong Hoang, and Alexander M. Rush. Structured attention networks.\\nIn International Conference on Learning Representations, 2017.\\n[17] Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.\\n[18] Oleksii Kuchaiev and Boris Ginsburg. Factorization tricks for LSTM networks. arXiv preprint\\narXiv:1703.10722, 2017.\\n[19] Zhouhan Lin, Minwei Feng, Cicero Nogueira dos Santos, Mo Yu, Bing Xiang, Bowen\\nZhou, and Yoshua Bengio. A structured self-attentive sentence embedding. arXiv preprint\\narXiv:1703.03130, 2017.\\n[20] Samy Bengio Łukasz Kaiser. Can active memory replace attention? In Advances in Neural\\nInformation Processing Systems, (NIPS), 2016.\\n10'), Document(metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 10, 'page_label': '11'}, page_content='[21] Minh-Thang Luong, Hieu Pham, and Christopher D Manning. Effective approaches to attention-\\nbased neural machine translation. arXiv preprint arXiv:1508.04025, 2015.\\n[22] Ankur Parikh, Oscar Täckström, Dipanjan Das, and Jakob Uszkoreit. A decomposable attention\\nmodel. In Empirical Methods in Natural Language Processing, 2016.\\n[23] Romain Paulus, Caiming Xiong, and Richard Socher. A deep reinforced model for abstractive\\nsummarization. arXiv preprint arXiv:1705.04304, 2017.\\n[24] Oﬁr Press and Lior Wolf. Using the output embedding to improve language models. arXiv\\npreprint arXiv:1608.05859, 2016.\\n[25] Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words\\nwith subword units. arXiv preprint arXiv:1508.07909, 2015.\\n[26] Noam Shazeer, Azalia Mirhoseini, Krzysztof Maziarz, Andy Davis, Quoc Le, Geoffrey Hinton,\\nand Jeff Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts\\nlayer. arXiv preprint arXiv:1701.06538, 2017.\\n[27] Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdi-\\nnov. Dropout: a simple way to prevent neural networks from overﬁtting. Journal of Machine\\nLearning Research, 15(1):1929–1958, 2014.\\n[28] Sainbayar Sukhbaatar, arthur szlam, Jason Weston, and Rob Fergus. End-to-end memory\\nnetworks. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors,\\nAdvances in Neural Information Processing Systems 28, pages 2440–2448. Curran Associates,\\nInc., 2015.\\n[29] Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural\\nnetworks. In Advances in Neural Information Processing Systems, pages 3104–3112, 2014.\\n[30] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, and Zbigniew Wojna.\\nRethinking the inception architecture for computer vision. CoRR, abs/1512.00567, 2015.\\n[31] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang\\nMacherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine\\ntranslation system: Bridging the gap between human and machine translation. arXiv preprint\\narXiv:1609.08144, 2016.\\n[32] Jie Zhou, Ying Cao, Xuguang Wang, Peng Li, and Wei Xu. Deep recurrent models with\\nfast-forward connections for neural machine translation. CoRR, abs/1606.04199, 2016.\\n11')]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(f\"Number of documents = {len(pdf_text)}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "BH6IAjYyWdpG",
        "outputId": "b44c453a-c14a-4d5d-a192-c95c92d4432b"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of documents = 11\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Chunk PDF text**"
      ],
      "metadata": {
        "id": "jLqBvd_JLTb-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def pdf_chunk(pdf_text: List[Document]) -> List[Document]:\n",
        "    \"\"\"\n",
        "    Splits extracted PDF text into smaller chunks using RecursiveCharacterTextSplitter.\n",
        "\n",
        "    Parameters:\n",
        "    pdf_text (List[Document]): A list of Document objects containing extracted text from a PDF.\n",
        "\n",
        "    Returns:\n",
        "    List[Document]: A list of chunked Document objects.\n",
        "    \"\"\"\n",
        "\n",
        "    print(\"PDF file text is chunked....\")\n",
        "    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)\n",
        "    chunks = text_splitter.split_documents(pdf_text)\n",
        "\n",
        "    return chunks"
      ],
      "metadata": {
        "id": "uK1aFrhvLWbp"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "chunks = pdf_chunk(pdf_text)"
      ],
      "metadata": {
        "id": "TdDmlfxkROZ_"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(f\"Number of chunks = {len(chunks)}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "3VzMTYugRRCW",
        "outputId": "0ca8bdd6-9196-48d1-b20e-39ae516c9b54"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of chunks = 40\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(chunks[0])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "B2wW4EJXXEo6",
        "outputId": "e09f1cff-f53b-404d-e4be-9c5e6cb28c2e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "page_content='Attention Is All You Need\n",
            "Ashish Vaswani∗\n",
            "Google Brain\n",
            "avaswani@google.com\n",
            "Noam Shazeer∗\n",
            "Google Brain\n",
            "noam@google.com\n",
            "Niki Parmar∗\n",
            "Google Research\n",
            "nikip@google.com\n",
            "Jakob Uszkoreit∗\n",
            "Google Research\n",
            "usz@google.com\n",
            "Llion Jones∗\n",
            "Google Research\n",
            "llion@google.com\n",
            "Aidan N. Gomez∗†\n",
            "University of Toronto\n",
            "aidan@cs.toronto.edu\n",
            "Łukasz Kaiser ∗\n",
            "Google Brain\n",
            "lukaszkaiser@google.com\n",
            "Illia Polosukhin∗‡\n",
            "illia.polosukhin@gmail.com\n",
            "Abstract\n",
            "The dominant sequence transduction models are based on complex recurrent or\n",
            "convolutional neural networks that include an encoder and a decoder. The best\n",
            "performing models also connect the encoder and decoder through an attention\n",
            "mechanism. We propose a new simple network architecture, the Transformer,\n",
            "based solely on attention mechanisms, dispensing with recurrence and convolutions\n",
            "entirely. Experiments on two machine translation tasks show these models to\n",
            "be superior in quality while being more parallelizable and requiring signiﬁcantly' metadata={'producer': 'PyPDF2', 'creator': 'PyPDF', 'creationdate': '', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'publisher': 'Curran Associates, Inc.', 'language': 'en-US', 'created': '2017', 'eventtype': 'Poster', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'title': 'Attention is All you Need', 'date': '2017', 'moddate': '2018-02-12T21:22:10-08:00', 'published': '2017', 'type': 'Conference Proceedings', 'firstpage': '5998', 'book': 'Advances in Neural Information Processing Systems 30', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'lastpage': '6008', 'source': 'attention_is_all_you_need.pdf', 'total_pages': 11, 'page': 0, 'page_label': '1'}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Create Vector Store**"
      ],
      "metadata": {
        "id": "FqAC3V1WLdtW"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Set the chroma DB path\n",
        "current_dir = \"/content/rag\"\n",
        "persistent_directory = os.path.join(current_dir, \"db\", \"chroma_db_pdf\")"
      ],
      "metadata": {
        "id": "qZ5ls-3uLh8s"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def create_vector_store(chunks: List[Document], db_path: str) -> Chroma:\n",
        "    \"\"\"\n",
        "    Creates a Chroma vector store from chunked documents.\n",
        "\n",
        "    Parameters:\n",
        "    chunks (List[Document]): A list of chunked Document objects.\n",
        "    db_path (str): The directory path to persist the vector store.\n",
        "\n",
        "    Returns:\n",
        "    Chroma: A Chroma vector store containing the embedded documents.\n",
        "    \"\"\"\n",
        "\n",
        "    print(\"Chrome vector store is created...\\n\")\n",
        "    embedding_model = OpenAIEmbeddings(model=\"text-embedding-3-small\")\n",
        "    db = Chroma.from_documents(documents=chunks, embedding=embedding_model, persist_directory=db_path)\n",
        "\n",
        "    return db"
      ],
      "metadata": {
        "id": "_30SvTV7Lg1K"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "db = create_vector_store(chunks, persistent_directory)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XS8knuW4RiQ8",
        "outputId": "d945639b-a6ef-4e32-b24b-0e5dc59d6b43"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Chrome vector store is created...\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Retrieve relevant chunks**"
      ],
      "metadata": {
        "id": "fV2W-AlfLwFX"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def retrieve_context(db: Chroma, query: str) -> List[Document]:\n",
        "    \"\"\"\n",
        "    Retrieves relevant document chunks from the Chroma vector store based on a query.\n",
        "\n",
        "    Parameters:\n",
        "    db (Chroma): The Chroma vector store containing embedded documents.\n",
        "    query (str): The query string to search for relevant document chunks.\n",
        "\n",
        "    Returns:\n",
        "    List[Document]: A list of retrieved relevant document chunks.\n",
        "    \"\"\"\n",
        "\n",
        "    retriever = db.as_retriever(search_type=\"similarity\", search_kwargs={\"k\": 2})\n",
        "    print(\"Relevant chunks are retrieved...\\n\")\n",
        "    relevant_chunks = retriever.invoke(query)\n",
        "\n",
        "    return relevant_chunks"
      ],
      "metadata": {
        "id": "7GPAc2iGL3bK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "query = \"Explain transformer model in one line\"\n",
        "\n",
        "relevant_chunks = retrieve_context(db, query)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "UO-clF3KRrZj",
        "outputId": "6cc84879-3f77-4b39-e5d9-b0e11d2513a9"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Relevant chunks are retrieved...\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(f\"Number of relevant chunks = {len(relevant_chunks)}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ytjpbOpaRzxI",
        "outputId": "36839684-ec88-4966-8fa2-b671afa175e6"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Number of relevant chunks = 2\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "for i, chunk in enumerate(relevant_chunks):\n",
        "  print(f\"Chunk-{i}\")\n",
        "  print(chunk)\n",
        "  print(\"\\n\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rk8DZzajR2Ya",
        "outputId": "7e61f5f6-ff2f-4e87-8234-c6ce8b9708a8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Chunk-0\n",
            "page_content='Figure 1: The Transformer - model architecture.\n",
            "wise fully connected feed-forward network. We employ a residual connection [10] around each of\n",
            "the two sub-layers, followed by layer normalization [ 1]. That is, the output of each sub-layer is\n",
            "LayerNorm(x+ Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer\n",
            "itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding\n",
            "layers, produce outputs of dimension dmodel = 512.\n",
            "Decoder: The decoder is also composed of a stack of N = 6identical layers. In addition to the two\n",
            "sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head\n",
            "attention over the output of the encoder stack. Similar to the encoder, we employ residual connections\n",
            "around each of the sub-layers, followed by layer normalization. We also modify the self-attention\n",
            "sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This' metadata={'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'book': 'Advances in Neural Information Processing Systems 30', 'created': '2017', 'creationdate': '', 'creator': 'PyPDF', 'date': '2017', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'eventtype': 'Poster', 'firstpage': '5998', 'language': 'en-US', 'lastpage': '6008', 'moddate': '2018-02-12T21:22:10-08:00', 'page': 2, 'page_label': '3', 'producer': 'PyPDF2', 'published': '2017', 'publisher': 'Curran Associates, Inc.', 'source': 'attention_is_all_you_need.pdf', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'title': 'Attention is All you Need', 'total_pages': 11, 'type': 'Conference Proceedings'}\n",
            "\n",
            "\n",
            "Chunk-1\n",
            "page_content='of continuous representations z = (z1,...,z n). Given z, the decoder then generates an output\n",
            "sequence (y1,...,y m) of symbols one element at a time. At each step the model is auto-regressive\n",
            "[9], consuming the previously generated symbols as additional input when generating the next.\n",
            "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully\n",
            "connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\n",
            "respectively.\n",
            "3.1 Encoder and Decoder Stacks\n",
            "Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two\n",
            "sub-layers. The ﬁrst is a multi-head self-attention mechanism, and the second is a simple, position-\n",
            "2' metadata={'author': 'Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin', 'book': 'Advances in Neural Information Processing Systems 30', 'created': '2017', 'creationdate': '', 'creator': 'PyPDF', 'date': '2017', 'description': 'Paper accepted and presented at the Neural Information Processing Systems Conference (http://nips.cc/)', 'description-abstract': 'The dominant sequence transduction models are based on complex recurrent orconvolutional neural networks in an encoder and decoder configuration. The best performing such models also connect the encoder and decoder through an attentionm echanisms.  We propose a novel, simple network architecture based solely onan attention mechanism, dispensing with recurrence and convolutions entirely.Experiments on two machine translation tasks show these models to be superiorin quality while being more parallelizable and requiring significantly less timeto train. Our single model with 165 million parameters, achieves 27.5 BLEU onEnglish-to-German translation, improving over the existing best ensemble result by over 1 BLEU. On English-to-French translation, we outperform the previoussingle state-of-the-art with model by 0.7 BLEU, achieving a BLEU score of 41.1.', 'editors': 'I. Guyon and U.V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett', 'eventtype': 'Poster', 'firstpage': '5998', 'language': 'en-US', 'lastpage': '6008', 'moddate': '2018-02-12T21:22:10-08:00', 'page': 1, 'page_label': '2', 'producer': 'PyPDF2', 'published': '2017', 'publisher': 'Curran Associates, Inc.', 'source': 'attention_is_all_you_need.pdf', 'subject': 'Neural Information Processing Systems http://nips.cc/', 'title': 'Attention is All you Need', 'total_pages': 11, 'type': 'Conference Proceedings'}\n",
            "\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Build context**"
      ],
      "metadata": {
        "id": "BcJbxTaqL7QE"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def build_context(relevant_chunks: List[Document]) -> str:\n",
        "    \"\"\"\n",
        "    Builds a context string from retrieved relevant document chunks.\n",
        "\n",
        "    Parameters:\n",
        "    relevant_chunks (List[Document]): A list of retrieved relevant document chunks.\n",
        "\n",
        "    Returns:\n",
        "    str: A concatenated string containing the content of the relevant chunks.\n",
        "    \"\"\"\n",
        "\n",
        "    print(\"Context is built from relevant chunks\")\n",
        "    context = \"\\n\\n\".join([chunk.page_content for chunk in relevant_chunks])\n",
        "\n",
        "    return context"
      ],
      "metadata": {
        "id": "xRZ2HLDxMAcP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "context = build_context(relevant_chunks)"
      ],
      "metadata": {
        "id": "Enka2YvTSULr"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "print(context)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "S3Ndsd-4SWg1",
        "outputId": "173620ee-b16b-4ec9-c83f-c58af5e6b330"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Figure 1: The Transformer - model architecture.\n",
            "wise fully connected feed-forward network. We employ a residual connection [10] around each of\n",
            "the two sub-layers, followed by layer normalization [ 1]. That is, the output of each sub-layer is\n",
            "LayerNorm(x+ Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer\n",
            "itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding\n",
            "layers, produce outputs of dimension dmodel = 512.\n",
            "Decoder: The decoder is also composed of a stack of N = 6identical layers. In addition to the two\n",
            "sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head\n",
            "attention over the output of the encoder stack. Similar to the encoder, we employ residual connections\n",
            "around each of the sub-layers, followed by layer normalization. We also modify the self-attention\n",
            "sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This\n",
            "\n",
            "of continuous representations z = (z1,...,z n). Given z, the decoder then generates an output\n",
            "sequence (y1,...,y m) of symbols one element at a time. At each step the model is auto-regressive\n",
            "[9], consuming the previously generated symbols as additional input when generating the next.\n",
            "The Transformer follows this overall architecture using stacked self-attention and point-wise, fully\n",
            "connected layers for both the encoder and decoder, shown in the left and right halves of Figure 1,\n",
            "respectively.\n",
            "3.1 Encoder and Decoder Stacks\n",
            "Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two\n",
            "sub-layers. The ﬁrst is a multi-head self-attention mechanism, and the second is a simple, position-\n",
            "2\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Combine all the steps into one function**"
      ],
      "metadata": {
        "id": "XDlTllCSMOSE"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "from typing import Dict\n",
        "from langchain.embeddings import OpenAIEmbeddings\n",
        "from langchain.vectorstores import Chroma\n",
        "\n",
        "def get_context(inputs: Dict[str, str]) -> Dict[str, str]:\n",
        "    \"\"\"\n",
        "    Creates or loads a vector store for a given PDF file and extracts relevant chunks based on a query.\n",
        "\n",
        "    Args:\n",
        "        inputs (Dict[str, str]): A dictionary containing the following keys:\n",
        "            - 'pdf_path' (str): Path to the PDF file.\n",
        "            - 'query' (str): The user query.\n",
        "            - 'db_path' (str): Path to the vector database.\n",
        "\n",
        "    Returns:\n",
        "        Dict[str, str]: A dictionary containing:\n",
        "            - 'context' (str): Extracted relevant context.\n",
        "            - 'query' (str): The user query.\n",
        "    \"\"\"\n",
        "    pdf_path, query, db_path  = inputs['pdf_path'], inputs['query'], inputs['db_path']\n",
        "\n",
        "    # Create new vector store if it does not exist\n",
        "    if not os.path.exists(db_path):\n",
        "        print(\"Creating a new vector store...\\n\")\n",
        "        pdf_text = pdf_extract(pdf_path)\n",
        "        chunks = pdf_chunk(pdf_text)\n",
        "        db = create_vector_store(chunks, db_path)\n",
        "\n",
        "    # Load the existing vector store\n",
        "    else:\n",
        "        print(\"Loading the existing vector store\\n\")\n",
        "        embedding_model = OpenAIEmbeddings(model=\"text-embedding-3-small\")\n",
        "        db = Chroma(persist_directory=db_path, embedding_function=embedding_model)\n",
        "\n",
        "    relevant_chunks = retrieve_context(db, query)\n",
        "    context = build_context(relevant_chunks)\n",
        "\n",
        "    return {'context': context, 'query': query}"
      ],
      "metadata": {
        "id": "cPKy-j4BMgHo"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Build RAG chain**"
      ],
      "metadata": {
        "id": "O2MVf4vxM4sv"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "template = \"\"\" You are an AI model trained for question answering. You should answer the\n",
        "  given question based on the given context only.\n",
        "  Question : {query}\n",
        "  \\n\n",
        "  Context : {context}\n",
        "  \\n\n",
        "  If the answer is not present in the given context, respond as: The answer to this question is not available\n",
        "  in the provided content.\n",
        "  \"\"\"\n",
        "\n",
        "rag_prompt = ChatPromptTemplate.from_template(template)\n",
        "\n",
        "llm = ChatOpenAI(model='gpt-4o-mini')\n",
        "\n",
        "str_parser = StrOutputParser()\n",
        "\n",
        "rag_chain = (\n",
        "    RunnableLambda(get_context)\n",
        "    | rag_prompt\n",
        "    | llm\n",
        "    | str_parser\n",
        ")"
      ],
      "metadata": {
        "id": "x9KX2O3OM8Yu"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## **Run RAG chain**"
      ],
      "metadata": {
        "id": "z-I63SUYNLT5"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Set the chroma DB path\n",
        "current_dir = \"/content/rag\"\n",
        "persistent_directory = os.path.join(current_dir, \"db\", \"chroma_db_pdf\")"
      ],
      "metadata": {
        "id": "ZiqL9tnZNQ1v"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Download the PDF file\n",
        "import requests\n",
        "\n",
        "pdf_url = 'https://proceedings.neurips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf'\n",
        "response = requests.get(pdf_url)\n",
        "\n",
        "pdf_path = 'attention_is_all_you_need.pdf'\n",
        "with open(pdf_path, 'wb') as file:\n",
        "    file.write(response.content)"
      ],
      "metadata": {
        "id": "MWOhvXCJMNsK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Write the query\n",
        "query = 'Explain transformer model in one line'"
      ],
      "metadata": {
        "id": "0WIwZN65NJLW"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "answer = rag_chain.invoke({'pdf_path':pdf_path, 'query':query, 'db_path':persistent_directory})"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "FkmSBhOJNKeC",
        "outputId": "1d69ce12-8c2a-4f8c-f889-96c3037da405"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Vector store already exists...\n",
            "\n",
            "Relevant chunks are retrieved...\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "print(f\"Query:{query}\\n\")\n",
        "print(f\"Generated answer:{answer}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "gyPrNA7iNSiR",
        "outputId": "0bd78608-fa86-41b9-ccd4-5e54c2c2eb68"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Query:Explain transformer model in one line\n",
            "\n",
            "Generated answer:The Transformer model is an architecture that uses stacked self-attention and fully connected layers for encoding and decoding sequences.\n"
          ]
        }
      ]
    }
  ]
}